package com.snda.sc.auth;

import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.springframework.util.StringUtils;

import com.snda.sc.exception.ParameterException;
import com.snda.sc.utils.ToStringHelper;

public class AuthParam {

	private HttpServletRequest request;

	public AuthParam(HttpServletRequest request) {
		this.request = request;
	}

	public String getRequired(String name) {
		String value = request.getParameter(name);
		if (value == null) throw new ParameterException(name);
		return value;
	}

	public String get(String name) {
		return request.getParameter(name);
	}

	public String getClientIp() {
		String clientIp = request.getHeader("x-forwarded-for");
		if (!StringUtils.hasLength(clientIp)) clientIp = request.getRemoteAddr();
		return clientIp;
	}

	@SuppressWarnings("unchecked")
	@Override
	public String toString() {
		ToStringHelper helper = new ToStringHelper(AuthParam.class);
		for (Object entry : request.getParameterMap().entrySet()) {
			Entry<String, String[]> e = (Entry<String, String[]>) entry;
			helper.append(e.getKey(), e.getValue()[0]);
		}
		return helper.toString();
	}
}